import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';
import {Injectable} from '@angular/core';
import {ResponseContentType} from '@angular/http';

@Injectable()
export class AuthHttp {

  constructor(private http: HttpClient) {
  }

  get<T>(url: string, options?: any, responseType?: string): Observable<T> {
    return this.http.get<T>(url, mergeToken(options, responseType));
  }

  post<T>(url: string, body: any | null, options?: any, responseType?: string): Observable<T> {
    return this.http.post<T>(url, body, mergeToken(options, responseType));
  }

  put<T>(url: string, body: any | null, options?: any, responseType?: string): Observable<T> {
    return this.http.put<T>(url, body, mergeToken(options, responseType));
  }

  delete<T>(url: string, options?: any | null, responseType?: string): Observable<T> {
    return this.http.delete<T>(url, mergeToken(options, responseType));
  }
}

const mergeToken = (options = {}, responseType = 'json') => {
  let accessToken = window.sessionStorage.getItem('accesstoken');
  if (accessToken === null) {
    accessToken = 'undefined';
  }
  const authHttpOption = {
    headers: new HttpHeaders({'Authz': accessToken}),
    responseType: responseType as 'json'
  };

  const mergedOptions = Object.assign(authHttpOption, options);
  return mergedOptions;
  // const newOptions = new RequestOptions({}).merge(options);
  // const newHeaders = new Headers(newOptions.headers);
  // const jwt = localStorage.getItem('jwt');
  // if (jwt) {
  //   newHeaders.set('authorization', `Bearer ${jwt}`);
  // }
  // newOptions.headers = newHeaders;
  // return newOptions;
};
